package cc.rengu.redp.bizimpl.upmp.controller;

/*import cc.rengu.ecp.core.util.PropertiesUtils;
import cc.rengu.ecp.platform.core.web.util.TokenUtil;*/

import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.request.MchntAreaListQueryRequest;
import cc.rengu.igas.bomp.facade.request.MchntInfoListQueryRequest;
import cc.rengu.igas.momp.facade.bean.McMchntInfoBean;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.MarketingAdsQueryVO;
import cc.rengu.redp.bizimpl.upmp.vo.MarketingMchntQueryVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 营销广告管理的控制类
 *
 * @author yuhongwen
 * @date 2020年04月08日08时23分
 */


@Api(tags = "营销管理:银行对收银员营销活动管理")
@Slf4j
@RestController
@RequestMapping("/admin/merParam/marketingAds")
public class MarketingAdsController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(MarketingAdsController.class);

    private long oprMenuId = 1;
    private String oprMenuName = "营销管理:营销广告管理";
    private long chkMenuId = 2;
    private String chkMenuName = "营销管理:营销广告管理审核";
    private String webNextUrl = "/admin/merParam/marketingAds/edit";

    @Autowired
    private IMarketingAdsService marketingAdsService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpSysSeqService sysSeqService;

    @Autowired
    private CommissionMarketService marketService;

    @Autowired
    private IUpmpUserInfoService upmpUserInfoService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private NtcAdvMchntAreaOrgservice ntcAdvMchntAreaOrgService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
//    @DubboReference(version = "2.2.0",url = "dubbo://172.17.100.9:62132",check = false)
    private BompMchntQueryService bompMchntQueryService;

    //    @RequiresPermissions("营销管理:营销广告管理")
    @GetMapping(value = "")
    public Map<String, String> index() {
        Map<String, String> result = new HashMap<>();
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        result.put("isAdmin", user.isAdmin() ? "1" : "0");
        result.put("instId", user.getInstId());
        return result;
    }

    //    @RequiresPermissions("营销管理:营销广告管理")
    @GetMapping(value = "/list")
    @ResponseBody
    public IPage<MarketingAds> findByPage(QueryRequest request, MarketingAdsQueryVO marketingAdsQueryVO) {
        IPage<MarketingAds> adsPage = marketingAdsService.marketingAdsSelectList(request, marketingAdsQueryVO);
        for (MarketingAds marketingAds : adsPage.getRecords()) {
            String isuId = marketingAds.getIsuId();
            if (Common.isNotBlank(isuId)) {
                LambdaQueryWrapper<UpmpUserInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UpmpUserInfo::getUserId, isuId);
                UpmpUserInfo user = upmpUserInfoService.getOne(wrapper);
                if (Common.isNotBlank(user)) {
                    marketingAds.setIsuId(user.getUserId());
                } else {
                    marketingAds.setIsuId(null);
                }
            }
        }
        return adsPage;
    }

    //    @RequiresPermissions(value = {"营销广告管理:新增", "营销广告管理:修改", "营销广告管理:发布", "营销广告管理:详情"}, logical = Logical.OR)
    @GetMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> editShow(@ModelAttribute("marketingAds") MarketingAds entity) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpSysParam dict = upmpSysParamService.findByPrimaryKey("marketOrgSelectedFlag", user.getInstId(), null);
        if (Common.isNotBlank(dict)) {
            result.put("marketOrgSelectedFlag", dict.getPrimaryValue());
        }
        //指定商户
        List<String> merchantList = new ArrayList<>();
        //指定商圈
        List<String> circleList = new ArrayList<>();
        //指定机构
        List<String> orgList = new ArrayList<>();
        String optFlag = entity.getOptFlag();
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            String instId = entity.getInstId() == null ? "" : entity.getInstId();
            String crtOrgId = "";
            if (user.isAdmin()) {
                if (StringUtils.isEmpty(instId)) {
                    log.error("联盟管理员新增数据必须先选择法人行！");
                    throw new RedpException("联盟管理员新增数据必须先选择法人行！");
                } else {
                    UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                    crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
                }
            } else {
                instId = (instId == null ? user.getInstId() : instId);
                crtOrgId = user.getOrgCode();
            }
            entity.setInstId(instId);
            entity.setStatus("00");
            entity.setPushAdModule("01");
/*            TokenUtil.getTokenByName(request, "img1Token");
            TokenUtil.getTokenByName(request, "img2Token");
            TokenUtil.getTokenByName(request, "img3Token");
            TokenUtil.getTokenByName(request, "img4Token");
            TokenUtil.getTokenByName(request, "img5Token");*/
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {//审核查询显示临时表数据，转换成对应实体

        } else {
            String instId = entity.getInstId();
            String adType = entity.getAdType();
            String marketingPagePath = "--".equals(entity.getMarketingPagePath()) ? "" : entity.getMarketingPagePath();
            String mainDataId = entity.getMainDataId();
            if (Common.isBlank(instId)) {
                logger.error("请求参数(instId)异常!");
                throw new RedpException("请求参数(instId)异常！");
            }
            if (Common.isBlank(adType)) {
                logger.error("请求参数(adType)异常!");
                throw new RedpException("请求参数(adType)异常！");
            }
            if (Common.isBlank(mainDataId)) {
                logger.error("请求参数(mainDataId)异常!");
                throw new RedpException("请求参数(mainDataId)异常！");
            }
            List<MarketingAds> list = marketingAdsService.findMarketingAds(instId, adType, mainDataId);
            List<NtcAdvMchntAreaOrg> ntcAdvMchntAreaOrgs = ntcAdvMchntAreaOrgService.queryMerchantListAndCircleList(mainDataId);
            for (NtcAdvMchntAreaOrg ntcAdvMchntAreaOrg : ntcAdvMchntAreaOrgs) {
                if ("0".equals(ntcAdvMchntAreaOrg.getSubjectTyp())) {
                    merchantList.add(ntcAdvMchntAreaOrg.getSubjectNo());
                } else if ("1".equals(ntcAdvMchntAreaOrg.getSubjectTyp())) {
                    circleList.add(ntcAdvMchntAreaOrg.getSubjectNo());
                } else if ("2".equals(ntcAdvMchntAreaOrg.getSubjectTyp())) {
                    orgList.add(ntcAdvMchntAreaOrg.getSubjectNo());
                } else {
                    //不作处理
                }
            }
            entity.setPushAdModule(list.get(0).getPushAdModule());
            entity.setCrtOrgId(list.get(0).getCrtOrgId());
            entity.setCreateTime(list.get(0).getCreateTime());
            entity.setAdDesc(list.get(0).getAdDesc());
            entity.setBeginTime(list.get(0).getBeginTime());
            entity.setExpireTime(list.get(0).getExpireTime());
            entity.setOprId(list.get(0).getOprId());
            entity.setStatus(list.get(0).getStatus());
            entity.setAdType(adType);
            entity.setInstId(instId);
            entity.setMarketingPagePath(marketingPagePath);
            entity.setMainDataId(mainDataId);
            List<Map<String, String>> list1 = new ArrayList<>();
            List<Map<String, String>> list2 = new ArrayList<>();
            for (int i = 1; i < 6; i++) {
                int num = 0;
                Map<String, String> map = new HashMap<>();
                Map<String, String> map1 = new HashMap<>();
                if (list != null) {
                    for (int j = 0; j < list.size(); j++) {
                        if (i == list.get(j).getImageIndex()) {
                            map.put("id", String.valueOf(list.get(j).getImageIndex()));
                            map.put("value", list.get(j).getImageLocalPath());
                            map1.put("id", String.valueOf(list.get(j).getImageIndex()));
                            String ImageLocalPath = Base64.getEncoder().encodeToString(list.get(j).getImageLocalPath().getBytes());
                            map1.put("src", ImageLocalPath);
                            map1.put("thumbnailSrc", list.get(j).getThumbnailPath());
                            map1.put("dataId", list.get(j).getId());
                            map1.put("imgTm", list.get(j).getPlayTm());
                            num++;
                            break;
                        }
                    }
                }
                if (num == 0) {
                    map.put("id", String.valueOf(i));
                    map.put("value", "");
                    map1.put("id", String.valueOf(i));
                    map1.put("src", "");
                    map1.put("thumbnailSrc", "");
                }
                list1.add(map);
                list2.add(map1);
            }
            result.put("list1", list2);
            result.put("list", list1);
            result.put("adType1", adType);
        /*    //图片上传
            if (list2 != null && list2.size() > 0) {
                list2.forEach(n -> TokenUtil.getTokenByName(request, "img" + n.get("id") + "Token"));
            }*/
        }
        result.put("merchantList", String.join(",", merchantList));
        result.put("circleList", String.join(",", circleList));
        result.put("orgList", orgList);
        result.put("entity", entity);
        result.put("optFlag", optFlag);
        return result;
    }

    //    @RequiresPermissions(value = {"营销广告管理:新增", "营销广告管理:修改"}, logical = Logical.OR)
    @PostMapping(value = "/edit")
    @ResponseBody
    public OperationResult editSave(@RequestBody MarketingAds entity) throws RedpException {
        String flag = entity.getOptFlag();
        String[] imgSrc = entity.getImgSrc();
        String[] imgThumbSrc = entity.getImgThumbSrc();
        String[] imgNo = entity.getImgNo();
        String[] imgTm = entity.getImgTm();
        String[] dataId = entity.getDataId();
        String mainDataId = entity.getMainDataId();
        String adType = entity.getAdType1();
        List circleList = entity.getCircleList();
        List merchantList = entity.getMerchantList();
        List orgInfoList = entity.getOrgInfoList();
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag))
            return marketingAdsService.saveData(String.valueOf(chkMenuId), chkMenuName, entity, webNextUrl, imgSrc, dataId, imgThumbSrc, imgNo, imgTm, mainDataId, adType);
        else {
            OperationResult operationResult = marketingAdsService.saveData(String.valueOf(oprMenuId), oprMenuName, entity, webNextUrl, imgSrc, dataId, imgThumbSrc, imgNo, imgTm, mainDataId, adType);
            Map data = (Map) operationResult.getData();
            mainDataId = (String) data.get("mainDataId");
            //修改保存前需要删除所有关联的广告与商户商圈机构关系
            if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
                ntcAdvMchntAreaOrgService.deleteMerchantListAndCircle(entity.getMainDataId());
            }
            //循环保存商圈与广告的关系
            if (circleList != null && circleList.size() > 0) {
                for (int i = 0; i < circleList.size(); i++) {
                    NtcAdvMchntAreaOrg entityNtcDev = new NtcAdvMchntAreaOrg();
                    if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
                        entityNtcDev.setNtcadvNo(entity.getMainDataId());
                    } else {
                        entityNtcDev.setNtcadvNo(mainDataId);
                    }
                    entityNtcDev.setNtcadvTyp("1");
                    entityNtcDev.setSubjectNo((String) circleList.get(i));
                    entityNtcDev.setSubjectTyp("1");
                    ntcAdvMchntAreaOrgService.saveData(entityNtcDev, entity.getOptFlag(), entity.getMainDataId(), organizationService);
                }
            }
            //循环保存商户与广告的关系
            if (merchantList != null && merchantList.size() > 0) {
                for (int i = 0; i < merchantList.size(); i++) {
                    NtcAdvMchntAreaOrg entityNtcDev = new NtcAdvMchntAreaOrg();
                    if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
                        entityNtcDev.setNtcadvNo(entity.getMainDataId());
                    } else {
                        entityNtcDev.setNtcadvNo(mainDataId);
                    }
                    entityNtcDev.setNtcadvTyp("1");
                    entityNtcDev.setSubjectNo((String) merchantList.get(i));
                    entityNtcDev.setSubjectTyp("0");
                    ntcAdvMchntAreaOrgService.saveData(entityNtcDev, entity.getOptFlag(), entity.getMainDataId(), organizationService);
                }
            }
            //循环保存机构与广告的关系
            if (orgInfoList != null && orgInfoList.size() > 0) {
                for (int i = 0; i < orgInfoList.size(); i++) {
                    NtcAdvMchntAreaOrg entityNtcDev = new NtcAdvMchntAreaOrg();
                    if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
                        entityNtcDev.setNtcadvNo(entity.getMainDataId());
                    } else {
                        entityNtcDev.setNtcadvNo(mainDataId);
                    }
                    entityNtcDev.setNtcadvTyp("1");
                    entityNtcDev.setSubjectNo((String) orgInfoList.get(i));
                    entityNtcDev.setSubjectTyp("2");
                    ntcAdvMchntAreaOrgService.saveData(entityNtcDev, entity.getOptFlag(), entity.getMainDataId(), organizationService);
                }
            }
            return operationResult;
        }
        //TODO 添加实际业务操作
    }


    //    @RequiresPermissions("营销广告管理:删除")
    @PostMapping(value = "/delete")
    @ResponseBody
    public OperationResult delete(HttpServletRequest request) throws RedpException {
        String instId = request.getParameter("instId");
        String adType = request.getParameter("adType");
        String mainDataId = request.getParameter("mainDataId");
        if (Common.isBlank(instId)) {
            logger.error("请求参数(instId)异常!");
            throw new RedpException("请求参数(instId)异常！");
        }
        if (Common.isBlank(adType)) {
            logger.error("请求参数(adType)异常!");
            throw new RedpException("请求参数(adType)异常！");
        }
        if (Common.isBlank(mainDataId)) {
            logger.error("请求参数(mainDataId)异常!");
            throw new RedpException("请求参数(mainDataId)异常！");
        }
        marketingAdsService.deleteMarketingAds(instId, adType, mainDataId);
        //删除关联的公告与商户商圈机构关系
        ntcAdvMchntAreaOrgService.deleteMerchantListAndCircle(mainDataId);
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        return OperationResult.buildSuccessResult("数据删除完成", result);
    }

    //    @RequiresPermissions("营销管理:营销广告管理")
    @PostMapping(value = "/release")
    @ResponseBody
    public OperationResult release(HttpServletRequest request) throws RedpException {
        String instId = request.getParameter("instId");
        String adType = request.getParameter("adType");
        String mainDataId = request.getParameter("mainDataId");
        if (Common.isBlank(instId)) {
            logger.error("请求参数(instId)异常!");
            throw new RedpException("请求参数(instId)异常！");
        }
        if (Common.isBlank(adType)) {
            logger.error("请求参数(adType)异常!");
            throw new RedpException("请求参数(adType)异常！");
        }
        if (Common.isBlank(mainDataId)) {
            logger.error("请求参数(mainDataId)异常!");
            throw new RedpException("请求参数(mainDataId)异常！");
        }
        marketingAdsService.releaseMarketingAds(instId, adType, mainDataId);
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        return OperationResult.buildSuccessResult("数据发布完成", result);
    }

    /**
     * 公告新增页查询商户或者商圈的名称
     *
     * @param
     * @param
     * @return
     */
    @PostMapping(value = "/getMerchanListNtc")
    @ResponseBody
    public OperationResult getMerchanListNtc(MarketingMchntQueryVO entity) {
        // 可成功添加的列表
        List<McMchntInfoBean> mchntInfoList = new ArrayList<>();
        // 存在错误的列表
        List<McMchntInfoBean> errorList = new ArrayList<>();

        String msg = "商户";
        if ("0".equals(entity.getMchntType())) {
            msg = "商户";
        } else {
            msg = "商圈";
        }
        try {
            if (StringUtils.isBlank(entity.getMchntNo())) {
                return OperationResult.buildFailureResult("请输入有效的" + msg + "号");
            }
            String[] merchantArr = entity.getMchntNo().split(",");
            List<String> strings = Arrays.asList(merchantArr);
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

            if ("0".equals(entity.getMchntType())) {
                //商户
                MchntInfoListQueryRequest param = new MchntInfoListQueryRequest();
                strings.forEach((e) -> {
                    param.setMchntNo(e);
                    Map<String, Object> maps = marketService.queryMcNoList(user, param, genMerOrder(user));
                    if (null != maps.get("results")) {
                        List resultList = (List) maps.get("results");
                        Map mcMap = (Map) resultList.get(0);
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo((String) mcMap.get("id"));
                        mchntInfo1.setMchntName((String) mcMap.get("name"));
                        mchntInfo1.setMchntType("0");//----0-商户 1-商圈
                        // 可成功添加
                        mchntInfoList.add(mchntInfo1);
                    } else {
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo(e);
                        mchntInfo1.setMchntType("0");//----0-商户 1-商圈
                        errorList.add(mchntInfo1);
                    }
                });
            } else {
                //商圈
                MchntAreaListQueryRequest param = new MchntAreaListQueryRequest();
                MchntInfoListQueryRequest mchntInfoParam = new MchntInfoListQueryRequest();
                strings.forEach((e) -> {
                    param.setMchntArea(e);
                    Map<String, Object> maps = marketService.queryMchntAreaList(user, param, bompMchntQueryService, genMerOrder(user));
                    if (null != maps.get("results")) {
                        List resultList = (List) maps.get("results");
                        Map mcMap = (Map) resultList.get(0);
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo((String) mcMap.get("id"));
                        mchntInfo1.setMchntName((String) mcMap.get("name"));
                        mchntInfo1.setMchntType("1");//----0-商户 1-商圈
                        // 可成功添加
                        mchntInfoList.add(mchntInfo1);
                    } else {
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo(e);
                        mchntInfo1.setMchntType("1");//----0-商户 1-商圈
                        errorList.add(mchntInfo1);
                    }
                });
            }
        } catch (Exception e) {
            log.error("获取" + msg + "信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("获取" + msg + "信息时系统异常");
        }
        Map<String, List<McMchntInfoBean>> resultMap = new HashMap<>();
        resultMap.put("successData", mchntInfoList);
        resultMap.put("errorData", errorList);
        return OperationResult.buildSuccessResult("查询成功", resultMap);
    }

    @RequiresPermissions("系统管理:公告管理")
    @PostMapping(value = "/uploadntc")
    @ResponseBody
    public OperationResult getDataFromExcelNtc(@RequestParam(value = "excelFile", required = false) MultipartFile excelFile, HttpServletRequest request) throws Exception {
        if (excelFile == null) {
            log.error("请选择文件");
            return OperationResult.buildFailureResult("请选择文件");
        }
        String originalFilename = excelFile.getOriginalFilename();
        if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
            log.error("文件不是excel类型");
            return OperationResult.buildFailureResult("文件不是excel类型");
        }
        // 可成功添加的列表
        List<McMchntInfoBean> mchntInfoList = new ArrayList<>();
        // 存在错误的列表
        List<McMchntInfoBean> errorList = new ArrayList<>();

        String selectedOrgInfoList = request.getParameter("selectedOrgInfoList");

        //
        Workbook workbook = null;
        if (originalFilename.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(excelFile.getInputStream());
        } else if (originalFilename.endsWith(".xls")) {
            workbook = new HSSFWorkbook(excelFile.getInputStream());
        } else {
            logger.info("类名-方法名", "MarketingAdsController-" + "getDataFromExcelNtc");
        }
        Sheet sheetAt = null;
        if (workbook != null) {
            sheetAt = workbook.getSheetAt(0);
        }
        int lastRowNum = sheetAt.getLastRowNum();
        if (lastRowNum > 500) {
            return OperationResult.buildFailureResult("上传数据不能超过500行");
        }
        if (lastRowNum < 1) {
            return OperationResult.buildFailureResult("请填入上传的商户号");
        }
        List<String> mcNos = new ArrayList<>();
        for (int i = 1; i <= lastRowNum; i++) {
            Row rowTitle = sheetAt.getRow(i);
            if (rowTitle != null) {// 行不为空
                // 读取cell
                Cell cell = rowTitle.getCell(0);
                if (cell != null) {
                    if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
                        return OperationResult.buildFailureResult("请将上传文件数据的格式设置为文本格式");
                    }

                    String mchntNo = CommonUtils.getValue(cell);
                    mcNos.add(mchntNo);
                }
            }
        }
        // 去重
        mcNos = mcNos.stream().distinct().collect(Collectors.toList());
        //
        MchntInfoListQueryRequest param = new MchntInfoListQueryRequest();
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        mcNos.forEach((e) -> {
            param.setMchntNo(e);
            Map<String, Object> maps = marketService.queryMcNoList(user, param, genMerOrder(user));
            if (null != maps.get("results")) {
                List resultList = (List) maps.get("results");
                Map mcMap = (Map) resultList.get(0);
                McMchntInfoBean mchntInfo = new McMchntInfoBean();
                mchntInfo.setMchntNo((String) mcMap.get("id"));
                mchntInfo.setMchntName((String) mcMap.get("name"));
                mchntInfo.setMchntType("0");//----0-商户 1-商圈

                Boolean isFeeMchntFlag = marketService.checkFeeMchnt(user, e, bompMchntQueryService, genMerOrder(user));
                // 可成功添加
                mchntInfoList.add(mchntInfo);
            } else {
                McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                mchntInfo1.setMchntNo(e);
                mchntInfo1.setMchntType("0");//----0-商户 1-商圈
                errorList.add(mchntInfo1);
            }
        });
        Map<String, List<McMchntInfoBean>> resultMap = new HashMap<>();
        resultMap.put("successData", mchntInfoList);
        resultMap.put("errorData", errorList);
        return OperationResult.buildSuccessResult("导入文件成功", resultMap);
    }

    /**
     * 生成交易流水号（格式：MO + 8位日期 + 8位顺序号）
     */

    public String genMerOrder(UpmpUserInfoVO user) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, user.getInstId());
        // 代理商编码前缀：MO（merOrder简写）
        String prefix = user.getInstId() + "MCMP";
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = sysSeqService.updateParamValue(paramCode, "MER_ORDER", channelId);
        // 8位日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date8 = sdf.format(new Date());

        // 商户订单号
        String merOrder = prefix + date8 + String.format("%08d", Integer.parseInt(seqNum));
        return merOrder;
    }


   /* @PostMapping(value = "/upload")
    @ResponseBody
    public OperationResult getDataFromExcel(@RequestParam(value = "excelFile", required = false) MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String no = request.getParameter("no");
        //校验商户号是否获取成功
        long size = excelFile.getSize();
        if (size > 104857760) {//文件不允许大于10M
            return OperationResult.buildSuccessResult("1", result);
        }
        String picLocalPath = "";
        String thumbnailLocalPath = "";
        String baseDir = PropertiesUtils.findPropertiesKey("/application.properties", "write_upload_file_dir");
        // 获取项目路径根目录
        if (Common.isBlank(baseDir)) {
            baseDir = request.getSession().getServletContext().getRealPath(File.separator);
        } else {
            picLocalPath = baseDir;
            // 去掉路径最后的“/”
            if (picLocalPath.endsWith(File.separator)) {
                picLocalPath = picLocalPath.substring(0, picLocalPath.length() - 1);
            }
        }
        // 去掉路径最后的“/”
        if (baseDir.endsWith(File.separator)) {
            baseDir = baseDir.substring(0, baseDir.length() - 1);
        }
        String uploadUrl = baseDir + File.separator + "upload" + File.separator + File.separator + "image" + File.separator;
        picLocalPath = File.separator + "upload" + File.separator + File.separator + "image" + File.separator;
        //String path = save +"upload/img";
        String path = uploadUrl;
        String carBinName = excelFile.getOriginalFilename();
        if (StringUtils.isBlank(carBinName)) {
            return OperationResult.buildSuccessResult("3", result);
        }
        if (!carBinName.endsWith(".jpg") && !carBinName.endsWith(".png") && !carBinName.endsWith(".gif") && !carBinName.endsWith(".jpeg")) {
            // 上传文件各种不正确
            return OperationResult.buildFailureResult("上传文件格式不正确", result);
        }
        //
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String lastUpddt = fmtdt.format(new Date());
        String fileName = lastUpddt + "_" + excelFile.getOriginalFilename();
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File targetFile = new File(path, fileName);
//		File pathDir = new File(path, "thumbnailFile");
        //  String picLocalPath = targetFile.getPath();//图片本地存放的目录
        picLocalPath = picLocalPath + fileName;
        File thumbnailFile = null;
        try {
            thumbnailFile = new File(path, lastUpddt + "_" + "thumbnailFile" + "_" + excelFile.getOriginalFilename());
            Thumbnails.of(excelFile.getInputStream()).scale(0.1f).toFile(thumbnailFile);
            excelFile.transferTo(targetFile);    //保存
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        thumbnailLocalPath = File.separator + "upload" + File.separator + File.separator + "image" + File.separator + lastUpddt + "_" + "thumbnailFile" + "_" + excelFile.getOriginalFilename();
//		String picType ="99";
//	    String picIndex ="01";
//        SignImage signImage = signImageService.findSignImage(img, picType, picIndex);
//        if(signImage ==null) {
//        	signImage = new SignImage(img, picType, picIndex, picLocalPath);
//        	signImage.setCrtTimestamp(lastUpddt);
//        }
//        signImage.setPicLocalPath(picLocalPath);
//        signImage.setLastUpdTimestamp(lastUpddt);
//        signImageService.save(signImage);
        result.put("id", "image_view" + no);
        if (thumbnailFile != null) {
            result.put("value", thumbnailFile.getName());
        }
        result.put("pathUrl", picLocalPath);
        result.put("thumbnailPathUrl", thumbnailLocalPath);
        return OperationResult.buildSuccessResult("上传成功", result);
    }
*/

}
